/**
 * 页面：数据看板（Dashboard）
 * 功能：顶部介绍、统计卡片与整体趋势图（ECharts 堆叠柱状图）
 * 细节：支持WebSocket实时更新，card模块使用随机数生成
 */
import { useEffect, useRef, useState } from 'react'
import * as echarts from 'echarts'

import './Index.css'

interface StatCard {
  id: string
  label: string
  value: number
  unit: string
  icon: string
  color: string
  trend?: number
}

function Index() {
  // 初始化卡片数据
  const [stats, setStats] = useState<StatCard[]>([
    { id: '1', label: '实时流量', value: 7120000, unit: '', icon: '👥', color: '#667eea' },
    { id: '2', label: '过去七天流量', value: 1500, unit: '', icon: '📈', color: '#60f0d3' },
    { id: '3', label: '过去30天流量', value: 158923, unit: '', icon: '✨', color: '#ffd64d' },
    { id: '4', label: '月卡用户', value: 1500, unit: '', icon: '💎', color: '#47a1ff' },
    { id: '5', label: '活跃用户', value: 125000, unit: '', icon: '🔥', color: '#ff6b9d' },
  ])

  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstanceRef = useRef<echarts.ECharts | null>(null)
  const wsRef = useRef<WebSocket | null>(null)
  const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const localUpdateTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
  const [wsStatus, setWsStatus] = useState<'connecting' | 'connected' | 'disconnected'>('disconnected')

  // 格式化数字显示
  const formatNumber = (num: number): string => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(2) + 'M'
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'K'
    }
    return num.toString()
  }

  // 初始化图表
  useEffect(() => {
    if (!chartRef.current) return
    const chart = echarts.init(chartRef.current)
    chartInstanceRef.current = chart
    
    const days = Array.from({ length: 30 }, (_, i) => i + 1)
    const s1 = days.map((d) => Math.round(200 + (d % 5) * 60 + Math.random() * 50))
    const s2 = days.map((d) => Math.round(120 + (d % 7) * 40 + Math.random() * 40))
    const s3 = days.map((d) => Math.round(80 + (d % 9) * 30 + Math.random() * 30))

    chart.setOption({
      grid: { left: 40, right: 20, top: 20, bottom: 40 },
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: days,
        axisLine: { lineStyle: { color: '#c9ceda' } },
        axisLabel: { color: '#6b7280' },
      },
      yAxis: {
        type: 'value',
        axisLine: { lineStyle: { color: '#c9ceda' } },
        splitLine: { lineStyle: { color: '#eef1f7' } },
        axisLabel: { color: '#6b7280' },
      },
      legend: { show: false },
      series: [
        { name: '微信公众号新增', type: 'bar', stack: 'total', data: s1, itemStyle: { color: '#60f0d3' }, barWidth: 14 },
        { name: 'App新增', type: 'bar', stack: 'total', data: s2, itemStyle: { color: '#ffd64d' } },
        { name: '第三方渠道', type: 'bar', stack: 'total', data: s3, itemStyle: { color: '#47a1ff' } },
      ],
    })

    const onResize = () => chart.resize()
    window.addEventListener('resize', onResize)
    return () => {
      window.removeEventListener('resize', onResize)
      chart.dispose()
      chartInstanceRef.current = null
    }
  }, [])

  // WebSocket连接和随机数更新
  useEffect(() => {
    // WebSocket服务器地址（如果未配置，使用本地模拟模式）
    const wsUrl = ((window as unknown as Record<string, string>).WS_URL) || null
    
    // 本地模拟随机数生成（当WebSocket不可用时）
    const startLocalRandomUpdate = () => {
      const updateRandomValues = () => {
        setStats((prevStats) => {
          return prevStats.map((stat) => {
            // 根据不同类型生成不同范围的随机数
            let newValue = stat.value
            let trend = 0
            
            switch (stat.id) {
              case '1': // 累计用户 - 大数，小幅波动
                trend = Math.floor(Math.random() * 200 - 100)
                newValue = Math.max(7100000, stat.value + trend)
                break
              case '2': // 过去七天新增 - 中等范围
                trend = Math.floor(Math.random() * 50 - 25)
                newValue = Math.max(1000, stat.value + trend)
                break
              case '3': // 过去30天新增 - 较大范围
                trend = Math.floor(Math.random() * 500 - 250)
                newValue = Math.max(150000, stat.value + trend)
                break
              case '4': // 月卡用户
                trend = Math.floor(Math.random() * 20 - 10)
                newValue = Math.max(1400, stat.value + trend)
                break
              case '5': // 活跃用户
                trend = Math.floor(Math.random() * 1000 - 500)
                newValue = Math.max(120000, stat.value + trend)
                break
            }
            
            return { ...stat, value: newValue, trend }
          })
        })
      }
      
      // 每2秒更新一次
      localUpdateTimerRef.current = setInterval(updateRandomValues, 2000)
      updateRandomValues() // 立即更新一次
    }

    // 尝试连接WebSocket
    const connectWebSocket = () => {
      if (!wsUrl) {
        // 没有WebSocket URL，使用本地模拟
        console.log('[Dashboard] WebSocket URL未配置，使用本地随机数生成')
        setWsStatus('disconnected')
        startLocalRandomUpdate()
        return
      }

      try {
        setWsStatus('connecting')
        const ws = new WebSocket(wsUrl)
        wsRef.current = ws

        ws.onopen = () => {
          console.log('[WebSocket] 连接成功')
          setWsStatus('connected')
          // 清除重连定时器和本地更新定时器
          if (reconnectTimerRef.current) {
            clearTimeout(reconnectTimerRef.current)
            reconnectTimerRef.current = null
          }
          if (localUpdateTimerRef.current) {
            clearInterval(localUpdateTimerRef.current)
            localUpdateTimerRef.current = null
          }
        }

        ws.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            
            // 更新统计数据
            if (data.stats && Array.isArray(data.stats)) {
              setStats((prevStats) => {
                return prevStats.map((prev, index) => {
                  const updated = data.stats[index]
                  if (updated) {
                    const newValue = typeof updated.value === 'number' ? updated.value : prev.value
                    const trend = newValue - prev.value
                    return { ...prev, value: newValue, trend }
                  }
                  return prev
                })
              })
            } else if (data.randomValues && Array.isArray(data.randomValues)) {
              // 如果接收到的是随机数数组
              setStats((prevStats) => {
                return prevStats.map((prev, index) => {
                  const randomValue = data.randomValues[index]
                  if (typeof randomValue === 'number') {
                    const trend = randomValue - prev.value
                    return { ...prev, value: randomValue, trend }
                  }
                  return prev
                })
              })
            }
            
            // 更新图表数据
            if (data.chartData && chartInstanceRef.current) {
              const chart = chartInstanceRef.current
              const currentOption = chart.getOption() as { series?: Array<{ data?: number[] }> }
              const currentSeries = currentOption.series || []
              
              const newSeries = [
                data.chartData.s1 ? { ...currentSeries[0], data: data.chartData.s1 } : currentSeries[0],
                data.chartData.s2 ? { ...currentSeries[1], data: data.chartData.s2 } : currentSeries[1],
                data.chartData.s3 ? { ...currentSeries[2], data: data.chartData.s3 } : currentSeries[2],
              ]
              
              chart.setOption({ series: newSeries })
            }
          } catch (error) {
            console.error('[WebSocket] 解析数据失败:', error)
          }
        }

        ws.onerror = () => {
          console.error('[WebSocket] 连接错误，切换到本地模式')
          setWsStatus('disconnected')
          // WebSocket连接失败，使用本地模拟
          startLocalRandomUpdate()
        }

        ws.onclose = () => {
          console.log('[WebSocket] 连接关闭，切换到本地模式')
          setWsStatus('disconnected')
          wsRef.current = null
          
          // 切换到本地模拟模式
          startLocalRandomUpdate()
          
          // 尝试重连（10秒后）
          if (!reconnectTimerRef.current && wsUrl) {
            reconnectTimerRef.current = setTimeout(() => {
              reconnectTimerRef.current = null
              connectWebSocket()
            }, 10000)
          }
        }
      } catch (error) {
        console.error('[WebSocket] 连接失败，使用本地模式:', error)
        setWsStatus('disconnected')
        startLocalRandomUpdate()
      }
    }

    // 开始连接
    connectWebSocket()

    // 清理函数
    return () => {
      if (wsRef.current) {
        wsRef.current.close()
        wsRef.current = null
      }
      if (reconnectTimerRef.current) {
        clearTimeout(reconnectTimerRef.current)
        reconnectTimerRef.current = null
      }
      if (localUpdateTimerRef.current) {
        clearInterval(localUpdateTimerRef.current)
        localUpdateTimerRef.current = null
      }
    }
  }, [])

  return (
    <div className="cards-dashboard">
      {/* WebSocket连接状态指示器 */}
      <div className="ws-status-indicator">
        <span className={`ws-status-dot ${wsStatus}`}></span>
        <span className="ws-status-text">
          {wsStatus === 'connected' ? '实时数据已连接' : 
           wsStatus === 'connecting' ? '正在连接...' : 
           '实时模式'}
        </span>
      </div>

      {/* 顶部介绍卡片 */}
      <section className="intro-card">
        <div className="intro-info">
          <div className="intro-title">数据洞察平台</div>
          <div className="intro-desc">整合多端数据，沉淀业务指标，帮助你快速做出决策。数据实时更新中...</div>
        </div>
        <a className="more-btn" href="http://47.94.196.176:9999/" target="_blank" rel="noreferrer">了解更多数字人大屏数据</a>
      </section>

      {/* 重新设计的统计卡片 */}
      <section className="stats-row">
        {stats.map((stat) => (
          <div className="stat-card-modern" key={stat.id} style={{ '--card-color': stat.color } as React.CSSProperties}>
            <div className="stat-card-header">
              <div className="stat-icon" style={{ background: `${stat.color}20`, color: stat.color }}>
                {stat.icon}
              </div>
              <div className="stat-label">{stat.label}</div>
            </div>
            <div className="stat-value-modern">
              <span className="stat-number">{formatNumber(stat.value)}</span>
              {stat.unit && <span className="stat-unit">{stat.unit}</span>}
            </div>
            {stat.trend !== undefined && stat.trend !== 0 && (
              <div className={`stat-trend ${stat.trend > 0 ? 'up' : 'down'}`}>
                <span className="trend-icon">{stat.trend > 0 ? '↑' : '↓'}</span>
                <span className="trend-value">{Math.abs(stat.trend)}</span>
              </div>
            )}
            <div className="stat-card-glow" style={{ background: `${stat.color}15` }}></div>
          </div>
        ))}
      </section>

      {/* 趋势卡片 */}
      <section className="trend-card">
        <div className="trend-header">
          <div className="trend-title">整体趋势</div>
          <div className="trend-actions">
            <div className="selector">上海 ▾</div>
            <div className="selector">2019-09-25 ▾</div>
          </div>
        </div>
        <div className="trend-tabs">
          <button className="tab-chip active">新增用户</button>
          <button className="tab-chip">累计用户</button>
          <button className="tab-chip">忠实用户</button>
          <button className="tab-chip">在线用户</button>
          <button className="tab-chip">月卡用户</button>
        </div>
        <div className="trend-body">
          <div ref={chartRef} className="echart" />
        </div>
        <div className="legend-row">
          <span className="legend-item l1" /> 微信公众号新增
          <span className="legend-item l2" /> App新增
          <span className="legend-item l3" /> 第三方渠道
        </div>
      </section>
    </div>
  )
}

export default Index
